const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');

const history = require('connect-history-api-fallback');

const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');

const index = require('./route');

const app = express();
app.use(express.json({ limit: '50mb' }));
app.use(express.static(path.join(__dirname, '../../public')));

app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({
    limit: '50mb',
    extended: true
}));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use('/', index);

app.use(
    history({
        verbose: true,
        rewrites: [
            // {//访问路径含dist则继续访问
            //   from: /^\/dist\/.*$/,
            //   to: function(context) {
            //     return context.parsedUrl.pathname;
            //   }
            // },
            // {//后缀为js|css 访问dist下相应文件
            //   from: /^\/.*[js|css]$/,
            //   to: function(context) {
            //     return '/dist/'+context.parsedUrl.pathname;
            //   }
            // },
            // {//访问路径不含dist则默认访问/dist/index.html
            //   from: /^\/.*$/,
            //   to: function(context) {
            //     return '/';
            //   }
            // },
        ],
    }),
);

if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, 'dist/')));
} else {
    const config = require('../../build/webpack.dev.conf');
    const compiler = webpack(config);
    // console.log(compiler)
    app.use(
        webpackDevMiddleware(compiler, {
            publicPath: config.output.publicPath,
            stats: { colors: true },
        }),
    );

    app.use(webpackHotMiddleware(compiler));
    app.use(express.static(path.join(__dirname, 'src/server/dist/')));
}

app.use('/', index);

// catch 404 and forward to error handler
app.use((req, res, next) => {
    const err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handler
app.use((err, req, res) => {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
